package com.htdz.util;

import com.htdz.entity.UsersInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RedisUtil {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);


    @Autowired
    public CommonRedisUtil commonRedisUtil;
    /***
     * 保存登陆信息到Redis
     * @param usersInfo
     */
    public  void saveUserInfo2Redis(UsersInfo usersInfo) {
        try {
            commonRedisUtil.getJedis().set("sessionUser_"+usersInfo.getUsersId(),JsonUtil.obj2json(usersInfo));

            logger.info("Logger==>RedisUtil==>saveUserInfo2Redis==>saveRedis:{}", JsonUtil.obj2json(usersInfo));
            logger.info(" KEY: "+ ("sessionUser_"+usersInfo.getUsersId()));

        } catch (Exception ex) {
            logger.error("Logger==>RedisUtil==>saveUserInfo2Redis==>Error:", ex);
        }
    }

    /**
     * 从redis中删除用户信息
     * @param usersInfo
     */
    public  void deleteUserInfo2Redis(UsersInfo usersInfo) {
        try {
            commonRedisUtil.getJedis().del("sessionUser_"+usersInfo.getUsersId());

            logger.info("Logger==>RedisUtil==>deleteUserInfo2Redis==>deleteUserInfo2Redis:{}", JsonUtil.obj2json(usersInfo));

        } catch (Exception ex) {
            logger.error("Logger==>RedisUtil==>deleteUserInfo2Redis==>Error:", ex);
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasExistKey(String key){
        return commonRedisUtil.getJedis().exists(key);
    }


    /**
     * 获取用户信息
     * @param usersId
     * @return
     */
    public UsersInfo getUsersInfo2Redis(Integer usersId){
        String result = null;
        try{
            result =commonRedisUtil.getJedis().get("sessionUser_"+usersId);
            logger.info("Logger==>RedisUtil==>getUsersInfo2Redis==>getUsersInfo2Redis:{}", JsonUtil.json2obj(result));
        }catch (Exception e){
            logger.error("Logger==>RedisUtil==>getUsersInfo2Redis==>Error:", e);
        }

        return JsonUtil.json2obj(result,UsersInfo.class);
    }

}
